package com.yeskery.nut.view.beetl;

import com.yeskery.nut.core.NutException;
import com.yeskery.nut.view.AbstractViewResolver;
import com.yeskery.nut.view.View;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.ResourceLoader;
import org.beetl.core.resource.ClasspathResourceLoader;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Locale;

/**
 * Beetl视图解析器
 * @author sprout
 * @version 1.0
 * 2022-07-02 16:29
 */
public class BeetlViewResolver extends AbstractViewResolver {

    /** 默认后缀名 */
    private static final String POSTFIX = "btl";

    /** 组合模板对象 */
    private final GroupTemplate groupTemplate;

    /**
     * 构建Beetl视图解析器
     */
    public BeetlViewResolver() {
        super(POSTFIX);
        try {
            ResourceLoader<String> resourceLoader = new ClasspathResourceLoader(this.getClass().getClassLoader(), "", StandardCharsets.UTF_8.name());
            this.groupTemplate = new GroupTemplate(resourceLoader, Configuration.defaultConfiguration());
        } catch (IOException e) {
            throw new NutException("Beetl Configuration Read Failure.", e);
        }
    }

    /**
     * 构建Beetl视图解析器
     * @param groupTemplate 组合模板对象
     */
    public BeetlViewResolver(GroupTemplate groupTemplate) {
        super(POSTFIX);
        this.groupTemplate = groupTemplate;
    }

    /**
     * 构建Beetl视图解析器
     * @param configuration Beetl配置对象
     */
    public BeetlViewResolver(Configuration configuration) {
        super(POSTFIX);
        ResourceLoader<String> resourceLoader = new ClasspathResourceLoader(this.getClass().getClassLoader(), "", StandardCharsets.UTF_8.name());
        this.groupTemplate = new GroupTemplate(resourceLoader, configuration);
    }

    @Override
    public View createView(String viewName, Locale locale) throws Exception {
        return new BeetlView(groupTemplate, viewName);
    }

    /**
     * 获取组合模板对象
     * @return 组合模板对象
     */
    public GroupTemplate getGroupTemplate() {
        return groupTemplate;
    }
}
